package com.katze.boot.plugins.security.handle;

import com.katze.common.ResponseStatus;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        int code = response.getStatus();
        if (code == 200) {
            response.setStatus(ResponseStatus.UNAUTHORIZED.value());
            response.getWriter().write("{\"code\":401,\"type\":\"error\",\"message\":\"权限不足\"}");
        } else {
            response.setStatus(ResponseStatus.UNAUTHORIZED.value());
            response.getWriter().write("{\"code\":" + code + ",\"type\":\"error\",\"message\":\"" + ResponseStatus.resolve(code) + "\"}");
        }
    }
}
